import { ref, reactive } from "vue"
import { updatepassword } from '~/api/manager'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { logout } from '~/api/manager'
import { showAlert, toast } from '~/composables/util'


// 密码重置封装方法
export function useRepassword() {

  const router = useRouter()
  const store = useStore()

  const formRef = ref(null)
  const formDrawerRef = ref(null)

  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: ''
  })

  const rules = {
    oldpassword: [
      {
        required: true,
        message: '旧密码不能为空',
        trigger: 'blur' // 触发器
      },
    ],
    password: [
      {
        required: true,
        message: '新密码不能为空',
        trigger: 'blur'	// 触发器
      }
    ],
    repassword: [
      {
        required: true,
        message: '确认密码不能为空',
        trigger: 'blur'	// 触发器
      }
    ]
  }

  const onSubmit = () => {
    formRef.value.validate((valid) => {
      // console.log(valid);
      if (!valid) {
        return false
      }
      // loading.value = true
      formDrawerRef.value.showLoading()
      updatepassword(form)
        .then(res => {
          toast("修改密码成功, 请重新登录")
          store.dispatch("logout")
          router.push("/login")
        }).finally(() => {
          // loading.value = false
          formDrawerRef.value.hideLoading()
        })
    })
  }

  const openRePassWordForm = () => formDrawerRef.value.open()

  return {
    formRef,
    formDrawerRef,
    form,
    rules,
    onSubmit,
    openRePassWordForm,
  }
}

export function useLogout() {

  const router = useRouter()
  const store = useStore()

  const handleLogout = () => {
    showAlert("是否确认退出登录?").then(res => {
      logout().finally(() => {
        store.dispatch("logout")
        // 跳转回登录页
        router.push("/login")
        // 提示退出成功
        toast("退出成功")
      })
    })
  }

  return {
    handleLogout
  }
}
